package com.coollang.smartbra.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.coollang.smartbra.MyAutoLayoutActivity;
import com.coollang.smartbra.R;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.dialog.ShareBitmapDialog;
import com.coollang.smartbra.http.HttpCallBack;
import com.coollang.smartbra.http.MyHttp;
import com.coollang.smartbra.model.RunningDataModel;
import com.coollang.smartbra.presenter.ShareMapActivityPresenter1;
import com.coollang.smartbra.utils.FormatUtils;
import com.coollang.smartbra.utils.TimeUtils;
import com.coollang.smartbra.utils.TranslucentSystemBarUtils;
import com.umeng.socialize.UMShareAPI;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;


/**
 * 跑步分享页面
 */

public class ShareMapActivity extends MyAutoLayoutActivity implements View.OnClickListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.map)
    MapView map;
    @BindView(R.id.ll_gps)
    LinearLayout llGps;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.run_speed)
    TextView runSpeed;
    @BindView(R.id.run_distance)
    TextView runDistance;
    @BindView(R.id.run_time)
    TextView runTime;
    @BindView(R.id.ll_run_small)
    LinearLayout llRunSmall;

    @BindView(R.id.tv_run_date)
    TextView tvRunDate;
    @BindView(R.id.content)
    LinearLayout content;
    @BindView(R.id.fl_map)
    FrameLayout flMap;
    @BindView(R.id.status_bar)
    View statusBar;
    @BindView(R.id.llcontent)
    LinearLayout llcontent;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.framelayout_map)
    public ImageView mFrameLayoutmap;

    //***********************数据相关*************************//

    private ShareMapActivityPresenter1 mPresenter;
    private ArrayList<LatLng> mLocationList;
    private ShareBitmapDialog mShareBitmapDialog;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        setContentView(R.layout.activity_sharemap);
        ButterKnife.bind(this);
        TranslucentSystemBarUtils.showChenJinZhuangTaiLan(statusBar, this, llcontent);
        map.onCreate(savedInstanceState);
        initViews();
        initBundle();
    }

    private void initBundle() {
        Intent intent = getIntent();
        if (intent != null) {
            mLocationList = getIntent().getParcelableArrayListExtra("latlnglist");
        }
    }


    @Override
    protected void initData() {
        super.initData();

        // 查询数据
        mPresenter = new ShareMapActivityPresenter1(this);
        mPresenter.setLocationList(mLocationList);
        mPresenter.initMap(map);
        mPresenter.addPolyline();

        queryData();
    }

    private void queryData() {
        // 数据
        RunningDataModel model = mPresenter.queryRunningData();

        setParams(model);

        long time = model.getLength();// 总时间
        long stepNum = model.getStep_nums();// 总步数
        double mileage = model.getMileage();// 总公里

        // 设置配速
        float v = (float) (mileage / time);

        // 保留小数点后2为
        String rate = new DecimalFormat("#0.00").format((v * 3600.00f));

        String[] split = rate.split("\\.");
        runSpeed.setText(split[0] + "'" + split[1] + "\"");

        // 设置时间
        runTime.setText(TimeUtils.getFormatTimeHHMMSS(time));

        // 设置公里数
        runDistance.setText(FormatUtils.decimalFormat((float) mileage));

    }

    // 上传跑步步数
    private void setParams(RunningDataModel model) {
        long time = model.getLength();// 总时间
        long stepNum = model.getStep_nums();// 总步数
        double mileage = model.getMileage();// 总公里
        int heart_rate = model.getHeart_rate();
        int max_rate = model.getMax_rate();
        int min_rate = model.getMin_rate();
        long starttime = model.getStarttime();
        long endtime = model.getEndtime();

        float frequency = stepNum / time;

        Map<String, String> params = new HashMap<>();
        params.put("username", MyApplication.mLogInDataBean.getUsername());
        params.put("type", "11");
        params.put("sport_duration", time + "");
        params.put("ave_heart_rate", heart_rate + "");
        params.put("max_heart_rate", max_rate + "");
        params.put("min_heart_rate", min_rate + "");
        params.put("start_time", starttime + "");
        params.put("end_time", endtime + "");
        params.put("distance", mileage + "");
        params.put("ave_pace", "0");
        params.put("max_pace", "0");
        params.put("min_pace", "0");
        params.put("frequency", frequency + "");

        MyHttp.getInstance().postRunningData(params, new HttpCallBack() {
            @Override
            public void onSuccess(String results, Call call, Response response) {
                Toast.makeText(ShareMapActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
            }

        });
    }

    protected void initViews() {
        findViewByIds();
        initListener();
    }

    private void findViewByIds() {
        tvTitle.setText(R.string.run_detail);
        tvTitle.setTextColor(getResources().getColor(R.color.black_80));
        ivRight.setBackgroundResource(R.drawable.icon_share);
        ivRight.setVisibility(View.VISIBLE);
        tvName.setText(MyApplication.userName);
        tvRunDate.setText(TimeUtils.getRunTime(System.currentTimeMillis()));
    }

    private void initListener() {
        ivRight.setOnClickListener(this);
        mIvBack.setOnClickListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        map.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        map.onResume();
    }


    //**********************************Activity管理地图的生命周期**********************************************//
    @Override
    protected void onDestroy() {
        super.onDestroy();
        map.onDestroy();
        UMShareAPI.get(this).release();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_right:
                mPresenter.screenShot();
                mPresenter.initShare();
                break;
            case R.id.iv_back:
                finishActivity();
                break;

        }
    }

    // ============================= 分享 =============================
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
